package algotithm.leetcode.bytedance.test15;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhouyanxiang
 * @Date 2021-03-2021/3/24-23:54
 */
public class Solution {

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        Solution s = new Solution();
        List<List<Integer>> list = s.threeSum(nums);
        for (List<Integer> res : list) {
            System.out.println(res);
        }
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length ;
        if (nums == null || len < 3) {
            return list;
        }
        for (int i = 0;i < len ; i++) {
            if(nums[i]  > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }

            int L = i + 1;
            int R = len - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    while (L < R && nums[L] == nums[L+1]) {
                        L++;
                    }
                    while (L < R && nums[R] == nums[R-1]) {
                        R--;
                    }
                    list.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    L++;
                    R--;
                } else if (sum > 0) {
                    R--;
                } else {
                    L++;
                }
            }
        }
        return list;
    }
}
